/******************************************************************************
 * Copyright (C) 2009 Low Heng Sin                                            *
 * Copyright (C) 2009 Idalica Corporation                                     *
 * This program is free software; you can redistribute it and/or modify it    *
 * under the terms version 2 of the GNU General Public License as published   *
 * by the Free Software Foundation. This program is distributed in the hope   *
 * that it will be useful, but WITHOUT ANY WARRANTY; without even the implied *
 * warranty of MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.           *
 * See the GNU General Public License for more details.                       *
 * You should have received a copy of the GNU General Public License along    *
 * with this program; if not, write to the Free Software Foundation, Inc.,    *
 * 59 Temple Place, Suite 330, Boston, MA 02111-1307 USA.                     *
 *****************************************************************************/
package org.compiere.apps.form;

import java.awt.BorderLayout;
import java.awt.Component;
import java.awt.GridBagConstraints;
import java.awt.GridBagLayout;
import java.awt.Insets;
import java.awt.event.ActionEvent;
import java.awt.event.ActionListener;
import java.beans.PropertyChangeEvent;
import java.beans.PropertyVetoException;
import java.beans.VetoableChangeListener;
import java.sql.PreparedStatement;
import java.sql.ResultSet;
import java.sql.SQLException;
import java.sql.Timestamp;
import java.text.DecimalFormat;
import java.util.ArrayList;
import java.util.List;
import java.util.Vector;
import java.util.logging.Level;

import javax.swing.ImageIcon;
import javax.swing.JButton;
import javax.swing.JLabel;
import javax.swing.JOptionPane;
import javax.swing.JScrollPane;
import javax.swing.JTable;
import javax.swing.JTree;
import javax.swing.SwingConstants;
import javax.swing.event.TableModelEvent;
import javax.swing.event.TableModelListener;
import javax.swing.table.AbstractTableModel;
import javax.swing.table.DefaultTableCellRenderer;
import javax.swing.table.DefaultTableModel;
import javax.swing.tree.DefaultMutableTreeNode;
import javax.swing.tree.DefaultTreeModel;
import javax.swing.tree.TreeCellRenderer;

import org.adempiere.exceptions.AdempiereException;
import org.adempiere.plaf.AdempierePLAF;
import org.compiere.apps.ADialog;
import org.compiere.apps.StatusBar;
import org.compiere.grid.ed.VDate;
import org.compiere.grid.ed.VLookup;
import org.compiere.minigrid.MiniTable;
import org.compiere.model.MLookup;
import org.compiere.model.MLookupFactory;
import org.compiere.model.Mzuser;
import org.compiere.model.X_A_Asset;
import org.compiere.plaf.CompiereColor;
import org.compiere.swing.CPanel;
import org.compiere.swing.CTextField;
import org.compiere.util.CLogger;
import org.compiere.util.DB;
import org.compiere.util.DisplayType;
import org.compiere.util.Env;
import org.compiere.util.KeyNamePair;
import org.compiere.util.Msg;
import org.compiere.model.Mzinvoice;


public class z_invoiceList //extends AssetTransfer
	implements FormPanel, ActionListener, TableModelListener, VetoableChangeListener
{
	private CPanel panel = new CPanel();
	public DecimalFormat format = DisplayType.getNumberFormat(DisplayType.Amount);
	/**	Logger			*/
	public static CLogger log = CLogger.getCLogger(VAssetTransfer.class);
	public int  m_C_BPartner_ID ;
	public int  m_C_BPartner2_ID;
	public int	total;
	public Timestamp transferDate = null;
	public int  m_AD_Org_ID = 0;
	private int         m_WindowNo = 0;
	/**	FormFrame			*/
	private FormFrame 	m_frame;

	private CPanel mainPanel = new CPanel();
	private BorderLayout mainLayout = new BorderLayout();
	private StatusBar statusBar = new StatusBar();
	
	CustNode selectNode;

	private static CLogger	s_log	= CLogger.getCLogger (Mzinvoice.class);
	
	class invoice{
		int zinvoice_id;
		int docno;
		Timestamp dateacct;
		String zuseridto;
		String status;
		
		
		
		public int getDocno() {
			return docno;
		}
		public void setDocno(int docno) {
			this.docno = docno;
		}
		public int getZinvoice_id() {
			return zinvoice_id;
		}
		public void setZinvoice_id(int zinvoice_id) {
			this.zinvoice_id = zinvoice_id;
		}
		public Timestamp getDateacct() {
			return dateacct;
		}
		public void setDateacct(Timestamp dateacct) {
			this.dateacct = dateacct;
		}
		public String getZuseridto() {
			return zuseridto;
		}
		public void setZuseridto(String zuseridto) {
			this.zuseridto = zuseridto;
		}
		public String getStatus() {
			return status;
		}
		public void setStatus(String status) {
			this.status = status;
		}
		
		
	}
	
	List<invoice> list = new ArrayList<invoice>();
	
	Mzuser zuser = null;
	
	/**
	 *	Initialize Panel
	 *  @param WindowNo window
	 *  @param frame frame
	 */
	public void init (int WindowNo, FormFrame frame)
	{
//		new zinvoice
		m_WindowNo = WindowNo;
		m_frame = frame;
		Env.setContext(Env.getCtx(), m_WindowNo, "IsSOTrx", "Y");   //  defaults to no
//		try
//		{
//			jbInit();
//	        initJtree();
//	        initJtable();
//			frame.getContentPane().add(mainPanel, BorderLayout.CENTER);
//			frame.getContentPane().add(statusBar, BorderLayout.SOUTH);
//		}
//		catch(Exception e)
//		{
//			log.log(Level.SEVERE, "", e);
//		}
		
        zlogin jd =  new zlogin(this, true);
        jd.setVisible(true);
        if(zuser != null){
        	try
    		{
        	 jbInit();
        	 
             initJtree();
             initJtable();
//             ListOfInvoices(zuser);
//             updateTable();
//             System.out.println("show lisofinv");
    		}
    		catch(Exception e)
    		{
    			log.log(Level.SEVERE, "", e);
    		}             
        }else{
//             System.out.println("close listofinv");
             m_frame.setVisible(false);
             //m_frame.hide();
             m_frame.dispose();
             
             
//             System.exit(0);
             
        }		
		
//		m_frame.setVisible(false);
		
		
	}	//	init

    private javax.swing.JButton jButton1;
    private javax.swing.JButton jButton2;
    private javax.swing.JButton jButton3;
    private javax.swing.JButton jButton4;
    private javax.swing.JButton jButton5;
    private javax.swing.JButton jButton6;
    private javax.swing.JLayeredPane jLayeredPane1;
    private javax.swing.JScrollPane jScrollPane1;
    private javax.swing.JScrollPane jScrollPane2;
    private javax.swing.JScrollPane jScrollPane3;
    private javax.swing.JScrollPane jScrollPane4;
    private javax.swing.JSplitPane jSplitPane1;
    private javax.swing.JTable jTable1;
    private javax.swing.JToolBar jToolBar1;
    private javax.swing.JTree jTree1;
	
	
    public void SetL(Mzuser b){
        zuser = b;
    }    

    class KeyIconCellRenderer extends DefaultTableCellRenderer {  
        public KeyIconCellRenderer() {  
            setIcon(new ImageIcon(getClass().getResource("images/new-icon.png")));  
        }  
    }
    
    private void updateTable(){

    	DefaultTableModel model = new DefaultTableModel(
                new Object [][] {
                },
                new String [] {
    	                        "№",
    	                        "Дата",
    	                        "Бизнес-партнер",
    	                        ""
                }
            );
    	
    	
    	for(invoice line: list){
    		ImageIcon iStatus = new ImageIcon(getClass().getResource("images/Flag-blue-icon.png"));
    		if(line.getStatus() != null){
    			
    			//send
    			if(line.getStatus().equals("SD"))		
    				iStatus = new ImageIcon(getClass().getResource("images/Flag-blue-icon.png"));
    			
    			//posted
    			else if(line.getStatus().equals("AP") )	
    				iStatus = new ImageIcon(getClass().getResource("images/Flag-green-icon.png"));
    			
    			//cancel
    			else if(line.getStatus().equals("CA"))	
    				iStatus = new ImageIcon(getClass().getResource("images/Flag-red-icon.png"));
    			
    				
    		}
//    		ImageIcon aboutIcon = new ImageIcon("about16.gif");
    		
    		 Object[] row = {line.getDocno(), line.getDateacct(),line.getZuseridto(), iStatus};
    		 model.addRow(row);
//    		 model.get
    	}
    	
    	jTable1.setModel(model);
        jTable1.setAutoResizeMode(jTable1.AUTO_RESIZE_OFF);
        jTable1.getColumnModel().getColumn(0).setPreferredWidth(30);
//        jTable1.getColumnModel().getColumn(0).
        jTable1.getColumnModel().getColumn(1).setPreferredWidth(70);
        jTable1.getColumnModel().getColumn(2).setPreferredWidth(200);
        jTable1.getColumnModel().getColumn(3).setPreferredWidth(20);
        
    }
    
    private void ListOfInvoices(int userid, int useridto, String typebox){
		
    	list.clear();
    	if(userid > 0 ){
	    	String sql = 
	    	" SELECT m.zinvoice_id, m.docno, m.dateacct " +		
	//    	"		,m.zuseridto	" +
	    	" ,(select name from adempiere.zuser where zuser_id = m.zuseridto) " + 		
	    	" ,m.status " +		
	    	" FROM adempiere.zinvoice as m " ;
	    	if(typebox.equals("inbox"))
	    		sql += 	" where m.zuseridto = ? and m.zuser_id = ? "; 
	    	else
	    		sql += 	" where m.zuser_id = ? ";
	    	
	    	
			PreparedStatement pstmt = null;
			ResultSet rs = null;
			try
			{
				pstmt = DB.prepareStatement (sql, null);
				
				pstmt.setInt(1, userid);
				if(typebox.equals("inbox"))
					pstmt.setInt(2, useridto);
				
				rs = pstmt.executeQuery();
				while (rs.next())
				{
					 invoice line = new invoice();
					 line.setZinvoice_id(rs.getInt(1));
					 line.setDocno(rs.getInt(2));
					 line.setDateacct(rs.getTimestamp(3));
					 line.setZuseridto(rs.getString(4));
					 line.setStatus(rs.getString(5));
					 list.add(line);
				}
				
				if(list.size() > 0){
					jButton3.setEnabled(true);
					jButton4.setEnabled(true);
				}else{
					jButton3.setEnabled(false);
					jButton4.setEnabled(false);
				}	
				updateTable();
			}
			catch (SQLException e)
			{
				s_log.log(Level.SEVERE, sql, e);
			}
			finally
			{
				DB.close(rs, pstmt);
				rs = null; pstmt = null;
			}
			}
		else 
			updateTable();
    
    
    }	
    private void jButton1ActionPerformed(java.awt.event.ActionEvent evt) {
    	if(selectNode != null)
	    	if(selectNode.getId() > 0)
	    		if(selectNode.getTypedoc().equals("inbox")){
		    		ListOfInvoices(zuser.get_ID(), selectNode.getId(), "inbox");	
	    		}else{
	    			ListOfInvoices(zuser.get_ID(), selectNode.getId(), "outbox");
	    		}
	    	else 
	    		ListOfInvoices(0, 0, "");
   }    
    
    //modify
    private void jButton4ActionPerformed(java.awt.event.ActionEvent evt) {
    	int row = jTable1.getSelectedRow();
    	if(row > -1){
    		new zinvoice(Env.getCtx(), list.get(row).getZinvoice_id(), zuser, "modify").setVisible(true);
    	}else
    		JOptionPane.showMessageDialog(null, "Выберите запись", "Редактирование записи", JOptionPane.WARNING_MESSAGE);
    }    
    
    //create
    private void jButton2ActionPerformed(java.awt.event.ActionEvent evt) {
        new zinvoice(Env.getCtx(), 0, zuser, "").setVisible(true);
    	if(selectNode != null)
	    	if(selectNode.getId() > 0)
	    		if(selectNode.getTypedoc().equals("inbox")){
		    		ListOfInvoices(zuser.get_ID(), selectNode.getId(), "inbox");	
	    		}else{
	    			ListOfInvoices(zuser.get_ID(), selectNode.getId(), "outbox");
	    		}
	    	else 
	    		ListOfInvoices(0, 0, "");
    }
    
    //delete
    private void jButton3ActionPerformed(java.awt.event.ActionEvent evt) {
//        new zinvoice(Env.getCtx(), 0).setVisible(true);
    	int row = jTable1.getSelectedRow();
    	
    	if(!list.get(row).getStatus().equals("AP")){
    	
	    	if(row > -1){
	    		if(JOptionPane.showConfirmDialog(null, "Удалить запись?", "Удаление записи", JOptionPane.OK_CANCEL_OPTION) == 0){
		    		Mzinvoice tmp = new Mzinvoice(Env.getCtx(), list.get(row).getZinvoice_id(), null);
		    		list.remove(row);
		    		tmp.delete(true);
		    		updateTable();
		    		jButton3.setEnabled(false);
		    		jButton4.setEnabled(false);
	    		}
	    	}else
	    		JOptionPane.showMessageDialog(null, "Выберите запись", "Удаление записи", JOptionPane.WARNING_MESSAGE);
	    	
    	}else
    		JOptionPane.showMessageDialog(null, "Счет-фактура подписана, удаление не возможно", "Удаление записи", JOptionPane.WARNING_MESSAGE);
    }        
    
    //accept
    private void jButton5ActionPerformed(java.awt.event.ActionEvent evt) {
    	int row = jTable1.getSelectedRow();
    	if(row > -1){
    		new zinvoice(Env.getCtx(), list.get(row).getZinvoice_id(), zuser, "accept").setVisible(true);
    	}else
    		JOptionPane.showMessageDialog(null, "Выберите запись", "Согласование записи", JOptionPane.WARNING_MESSAGE);
    }
    
    //accept
    private void jButton6ActionPerformed(java.awt.event.ActionEvent evt) {
    	int row = jTable1.getSelectedRow();
    	if(row > -1){
    		new zinvoice(Env.getCtx(), list.get(row).getZinvoice_id(), zuser, "view").setVisible(true);
    		
    	}else
    		JOptionPane.showMessageDialog(null, "Выберите запись", "Просмотр записи", JOptionPane.WARNING_MESSAGE);
    }    
    
	private void jbInit() throws Exception
	{
	    jScrollPane1 = new javax.swing.JScrollPane();
        jLayeredPane1 = new javax.swing.JLayeredPane();
        jToolBar1 = new javax.swing.JToolBar();
        jButton1 = new javax.swing.JButton();
        jButton2 = new javax.swing.JButton();
        jButton4 = new javax.swing.JButton();
        jButton3 = new javax.swing.JButton();
        jButton5 = new javax.swing.JButton();
        jButton6 = new javax.swing.JButton();
        jSplitPane1 = new javax.swing.JSplitPane();
        jScrollPane3 = new javax.swing.JScrollPane();
        jTree1 = new javax.swing.JTree();
        jScrollPane4 = new javax.swing.JScrollPane();
        jScrollPane2 = new javax.swing.JScrollPane();
        jTable1 = new javax.swing.JTable(){
	        public Class getColumnClass(int column)
	        {
	            return getValueAt(0, column).getClass();
	        }
        };

//        setDefaultCloseOperation(javax.swing.WindowConstants.EXIT_ON_CLOSE);
        m_frame.setFont(new java.awt.Font("Tahoma", 1, 10)); // NOI18N
        m_frame.setResizable(false);

        jToolBar1.setFloatable(false);
        jToolBar1.setRollover(true);

        jButton1.setFont(new java.awt.Font("Tahoma", 0, 10)); // NOI18N
        jButton1.setIcon(new javax.swing.ImageIcon(getClass().getResource("images/1356107256_reload.png"))); // NOI18N
        jButton1.setText("Обновить");
        jButton1.setFocusable(false);
        jButton1.setHorizontalTextPosition(javax.swing.SwingConstants.CENTER);
        jButton1.setVerticalTextPosition(javax.swing.SwingConstants.BOTTOM);
        jButton1.addActionListener(new java.awt.event.ActionListener() {
            public void actionPerformed(java.awt.event.ActionEvent evt) {
            	jButton1ActionPerformed(evt);
            }
        });        
        jToolBar1.add(jButton1);

        jButton2.setFont(new java.awt.Font("Tahoma", 0, 10)); // NOI18N
        jButton2.setIcon(new javax.swing.ImageIcon(getClass().getResource("images/new-icon.png"))); // NOI18N
        jButton2.setText("Создать");
        jButton2.setFocusable(false);
        jButton2.setHorizontalTextPosition(javax.swing.SwingConstants.CENTER);
        jButton2.setVerticalTextPosition(javax.swing.SwingConstants.BOTTOM);
        jButton2.addActionListener(new java.awt.event.ActionListener() {
            public void actionPerformed(java.awt.event.ActionEvent evt) {
            	jButton2ActionPerformed(evt);
            }
        });
        jToolBar1.add(jButton2);

        jButton4.setFont(new java.awt.Font("Tahoma", 0, 10)); // NOI18N
        jButton4.setIcon(new javax.swing.ImageIcon(getClass().getResource("images/1356106580_edit-notes.png"))); // NOI18N
        jButton4.setText("Изменить");
        jButton4.setFocusable(false);
        jButton4.setHorizontalTextPosition(javax.swing.SwingConstants.CENTER);
        jButton4.setVerticalTextPosition(javax.swing.SwingConstants.BOTTOM);
        jButton4.addActionListener(new java.awt.event.ActionListener() {
            public void actionPerformed(java.awt.event.ActionEvent evt) {
            	jButton4ActionPerformed(evt);
            }
        });        
        jToolBar1.add(jButton4);

        jButton6.setFont(new java.awt.Font("Tahoma", 0, 10)); // NOI18N
        jButton6.setIcon(new javax.swing.ImageIcon(getClass().getResource("images/application-view-list-icon.png"))); // NOI18N
        jButton6.setText("Просмотреть");
        jButton6.setFocusable(false);
        jButton6.setHorizontalTextPosition(javax.swing.SwingConstants.CENTER);
        jButton6.setVerticalTextPosition(javax.swing.SwingConstants.BOTTOM);
        jButton6.addActionListener(new java.awt.event.ActionListener() {
            public void actionPerformed(java.awt.event.ActionEvent evt) {
            	jButton6ActionPerformed(evt);
            }
        });        
        jToolBar1.add(jButton6);
        
        
        jButton3.setFont(new java.awt.Font("Tahoma", 0, 10)); // NOI18N
        jButton3.setIcon(new javax.swing.ImageIcon(getClass().getResource("images/1356106657_delete.png"))); // NOI18N
        jButton3.setText("Удалить");
        jButton3.setFocusable(false);
        jButton3.setHorizontalTextPosition(javax.swing.SwingConstants.CENTER);
        jButton3.setVerticalTextPosition(javax.swing.SwingConstants.BOTTOM);
        jButton3.addActionListener(new java.awt.event.ActionListener() {
            public void actionPerformed(java.awt.event.ActionEvent evt) {
            	jButton3ActionPerformed(evt);
            }
        });
        jToolBar1.add(jButton3);

        jButton5.setFont(new java.awt.Font("Tahoma", 0, 10)); // NOI18N
        jButton5.setIcon(new javax.swing.ImageIcon(getClass().getResource("images/ok-icon.png"))); // NOI18N
        jButton5.setText("Принять");
        jButton5.setFocusable(false);
        jButton5.setHorizontalTextPosition(javax.swing.SwingConstants.CENTER);
        jButton5.setVerticalTextPosition(javax.swing.SwingConstants.BOTTOM);
        jButton5.addActionListener(new java.awt.event.ActionListener() {
            public void actionPerformed(java.awt.event.ActionEvent evt) {
            	jButton5ActionPerformed(evt);
            }
        });        
        jToolBar1.add(jButton5);
        
        jToolBar1.setBounds(0, 0, 950, 63);
        jLayeredPane1.add(jToolBar1, javax.swing.JLayeredPane.DEFAULT_LAYER);

        jSplitPane1.setDividerLocation(150);
        jSplitPane1.setDividerSize(2);

        jTree1.setFont(new java.awt.Font("Tahoma", 0, 10)); // NOI18N
        jTree1.setRootVisible(false);
        jTree1.addTreeSelectionListener(new javax.swing.event.TreeSelectionListener() {
            public void valueChanged(javax.swing.event.TreeSelectionEvent evt) {
                jTree1ValueChanged(evt);
            }
        });
        jScrollPane3.setViewportView(jTree1);

        jSplitPane1.setLeftComponent(jScrollPane3);

        jTable1.setFont(new java.awt.Font("Tahoma", 0, 10)); // NOI18N
        jTable1.getTableHeader().setFont(new java.awt.Font("Tahoma", 0, 10));
        jTable1.setModel(new javax.swing.table.DefaultTableModel(
            new Object [][] {
            },
            new String [] {
	                        "№",
	                        "Дата",
	                        "Бизнес-партнер",
	                        "Статус"
            }
        ));
        
        jScrollPane2.setViewportView(jTable1);

        jScrollPane4.setViewportView(jScrollPane2);

        jSplitPane1.setRightComponent(jScrollPane4);

        jSplitPane1.setBounds(0, 60, 730, 460);
        jLayeredPane1.add(jSplitPane1, javax.swing.JLayeredPane.DEFAULT_LAYER);

        jScrollPane1.setViewportView(jLayeredPane1);

        javax.swing.GroupLayout layout = new javax.swing.GroupLayout(m_frame.getContentPane());
        m_frame.getContentPane().setLayout(layout);
        layout.setHorizontalGroup(
            layout.createParallelGroup(javax.swing.GroupLayout.Alignment.LEADING)
            .addComponent(jScrollPane1, javax.swing.GroupLayout.PREFERRED_SIZE, 730, javax.swing.GroupLayout.PREFERRED_SIZE)
        );
        layout.setVerticalGroup(
            layout.createParallelGroup(javax.swing.GroupLayout.Alignment.LEADING)
            .addComponent(jScrollPane1, javax.swing.GroupLayout.DEFAULT_SIZE, 520, Short.MAX_VALUE)
        );

        m_frame.pack();
	}   //  jbInit

	/**
	 * 	Dispose
	 */
	public void dispose()
	{
		if (m_frame != null)
			m_frame.dispose();
		m_frame = null;
	}	//	dispose

    private void jTree1ValueChanged(javax.swing.event.TreeSelectionEvent evt) {
    	
    	Object custNode = evt.getNewLeadSelectionPath().getLastPathComponent();
    	DefaultMutableTreeNode custNode2 = (DefaultMutableTreeNode) custNode;
    	CustNode custNode3 = (CustNode) custNode2.getUserObject();
    	
    	
    	if(custNode3.getId() > 0)
    		if(custNode3.getTypedoc().equals("inbox")){
	    		ListOfInvoices(zuser.get_ID(), custNode3.getId(), "inbox");	
    			selectNode = custNode3;
    		}else{
    			ListOfInvoices(zuser.get_ID(), custNode3.getId(), "outbox");
    			selectNode = custNode3;
    		}
    	else 
    		ListOfInvoices(0, 0, "");
    }
	
	/**
	 *  Dynamic Init (prepare dynamic fields)
	 *  @throws Exception if Lookups cannot be initialized
	 */
	public void dynInit() throws Exception
	{
	}   //  dynInit

	@Override
	public void vetoableChange(PropertyChangeEvent evt)
			throws PropertyVetoException {
		// TODO Auto-generated method stub
		
	}

	@Override
	public void tableChanged(TableModelEvent e) {
		// TODO Auto-generated method stub
		
	}

	@Override
	public void actionPerformed(ActionEvent e) {
		// TODO Auto-generated method stub
		
	}
	
	private void  initJtree(){
        jTree1.setModel(new DefaultTreeModel(getJtreeModel())); 
        jTree1.setCellRenderer(new CustTreeCellRenderer());
        
        for (int i = 0; i < jTree1.getRowCount(); i++) {
            jTree1.expandRow(i);
        }
        
	}
	
	private DefaultMutableTreeNode getJtreeModel(){
	
		DefaultMutableTreeNode model = new DefaultMutableTreeNode();
			
		CustNode custNode = new CustNode(0, "Входящие", "inbox-download-icon.png", "inbox");
		DefaultMutableTreeNode nodeIn = new DefaultMutableTreeNode(custNode);
		model.add(nodeIn);
				custNode = new CustNode(0, "2013", "mail-open-table-icon.png", "inbox");
				DefaultMutableTreeNode n2013 = new DefaultMutableTreeNode(custNode);
				nodeIn.add(n2013);
				
					getInbox(n2013);
						
//					custNode = new CustNode("User001", "man-icon.png", "inbox");
//			 		DefaultMutableTreeNode nuser000 = new DefaultMutableTreeNode(custNode);
//			 		n2013.add(nuser000);		 

		
		custNode = new CustNode(0,"Исходящие", "inbox-upload-icon.png", "outbox");
		DefaultMutableTreeNode nodeOut = new DefaultMutableTreeNode(custNode);
		model.add(nodeOut);
				custNode = new CustNode(0,"2013", "mail-open-table-icon.png", "outbox");
				DefaultMutableTreeNode n2013out = new DefaultMutableTreeNode(custNode);
				nodeOut.add(n2013out);
					custNode = new CustNode(zuser.get_ID(), zuser.getName(), "man-icon.png", "outbox");
			 		DefaultMutableTreeNode nuser000out = new DefaultMutableTreeNode(custNode);
			 		n2013out.add(nuser000out);			 		
			 		
//	 DefaultMutableTreeNode nodeOut =new DefaultMutableTreeNode("Исходящие");
//	 model.add(nodeOut);
	return model;        
	}
	
	private DefaultMutableTreeNode getInbox(DefaultMutableTreeNode root){
		DefaultMutableTreeNode n2013 = root;
		
    	String sql = 
    			"	select u.zuser_id, u.name	" +
    			"	from adempiere.zuser u, adempiere.zinvoice i	" +
    			"	where i.zuser_id = u.zuser_id	" +
    			"	and i.zuseridto = ?	" +
    			"	group by u.zuser_id 	";    	
    	
		PreparedStatement pstmt = null;
		ResultSet rs = null;
		try
		{
			pstmt = DB.prepareStatement (sql, null);
			pstmt.setInt(1, zuser.get_ID());
			rs = pstmt.executeQuery();
			while (rs.next())
			{
				CustNode custNode = new CustNode(rs.getInt(1), rs.getString(2), "man-icon.png", "inbox");
		 		DefaultMutableTreeNode nuser000 = new DefaultMutableTreeNode(custNode);
		 		n2013.add(nuser000);		 

			}
			
			updateTable();
		}
		catch (SQLException e)
		{
			s_log.log(Level.SEVERE, sql, e);
		}
		finally
		{
			DB.close(rs, pstmt);
			rs = null; pstmt = null;
		}
		
		
		return n2013;
	} 
	
	
	private void initJtable(){
//        jTable1 = new JTable(new DefaultTableModel(new Object[]{"Column1", "Column2"}));
        jTable1.setAutoResizeMode(jTable1.AUTO_RESIZE_OFF);
        jTable1.getColumnModel().getColumn(0).setPreferredWidth(30);
        jTable1.getColumnModel().getColumn(1).setPreferredWidth(70);
        jTable1.getColumnModel().getColumn(2).setPreferredWidth(200);
        jTable1.getColumnModel().getColumn(3).setPreferredWidth(10);
        jTable1.getColumnModel().getColumn(3).setCellRenderer(new KeyIconCellRenderer());
	};
	
    class CustTreeCellRenderer implements TreeCellRenderer {
        private JLabel label;
 
        CustTreeCellRenderer() {
            label = new JLabel();
        }
 

		@Override
		public Component getTreeCellRendererComponent(JTree tree, Object value,
				boolean selected, boolean expanded, boolean leaf, int row,
				boolean hasFocus) {
            Object o = ((DefaultMutableTreeNode) value).getUserObject();
//            selected = true;
//            expanded = true;
            label.setFont(new java.awt.Font("Tahoma", 0, 10));
            if (o instanceof CustNode) {
            	CustNode custNode = (CustNode) o;
            	label.setIcon(new ImageIcon(getClass().getResource("images/" + custNode.getFlagIcon())));
//                label.setIcon(new ImageIcon(custNode.getFlagIcon()));
                label.setText(custNode.getName());
                label.setFocusable(true);
            } else {
                label.setIcon(null);
                label.setText("" + value);
            }
            return label;
		}
    }
 
    class CustNode {
    	private int id;
        private String name;
        private String flagIcon;
        private String typedoc;
 
        CustNode(int id, String name, String flagIcon, String typedoc) {
        	this.id = id;
            this.name = name;
            this.flagIcon = flagIcon;
            this.typedoc = typedoc;
        }
 
        public String getName() {
            return name;
        }
 
        public void setName(String name) {
            this.name = name;
        }
 
        public String getFlagIcon() {
            return flagIcon;
        }
 
        public void setFlagIcon(String flagIcon) {
            this.flagIcon = flagIcon;
        }

		public String getTypedoc() {
			return typedoc;
		}

		public void setTypedoc(String typedoc) {
			this.typedoc = typedoc;
		}

		public int getId() {
			return id;
		}

		public void setId(int id) {
			this.id = id;
		}
        
        
        
    }	
	
//	class MyTableModel extends AbstractTableModel {
//	    String[] columnNames = {
//	                        "№",
//	                        "Дата",
//	                        "Бизнес-партнер",
//	                        "Статус"
//	                       };
//	    
//	    Object[][] data;
////	    for(int i=0; i < 10; i++){
////	    	
////	    }
//	    
////	    = {{0,"","",""},{0,"","",""},{0,"","",""},{0,"","",""},{0,"","",""},{0,"","",""},{0,"","",""},{0,"","",""},{0,"","",""},{0,"","",""}
////	                    {   new Integer(1), 
////	                        "01.12.2012", 
////	                        "ТОО Digital-Kazakhstan.", 
////	                        "Завершенно"
////	                    },
////	                    {   new Integer(2), 
////	                        "05.12.2012", 
////	                        "ТОО Астана-сервис.",
////	                        "На согласовании"
////	                    },
////	                    {   new Integer(3), 
////	                        "07.12.2012", 
////	                        "АО Oracle.",
////	                        "Отменнено"
////	                    }                    
////	    };
//
//	    public int getColumnCount() {
//	        return columnNames.length;
//	    }
//
//	    public int getRowCount() {
//	        return data.length;
//	    }
//
//	    public String getColumnName(int col) {
//	        return columnNames[col];
//	    }
//
//	    public Object getValueAt(int row, int col) {
//	        return data[row][col];
//	    }
//
//	    public Class getColumnClass(int c) {
//	        return getValueAt(0, c).getClass();
//	    }
//
//	    /*
//	     * Don't need to implement this method unless your table's
//	     * editable.
//	     */
//	    public boolean isCellEditable(int row, int col) {
//	        //Note that the data/cell address is constant,
//	        //no matter where the cell appears onscreen.
//	        if (col < 2) {
//	            return false;
//	        } else {
//	            return true;
//	        }
//	    }
//
//	    /*
//	     * Don't need to implement this method unless your table's
//	     * data can change.
//	     */
//	    public void setValueAt(Object value, int row, int col) {
//	        data[row][col] = value;
//	        fireTableCellUpdated(row, col);
//	    }
//	    
//	}   	
}
